/*Author: Rony Lahav (ID:043489889)*/

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class SingleTCPOutgoingConnectionSN extends SingleTCPOutgoingConnection implements Runnable{

	DBTuple senderTuple;
	String senderID;
	
	public SingleTCPOutgoingConnectionSN(String IP, int TCPPort, String fileName, int fileSize, long uniqueID, String senderKey, String senderID) {
		super(IP, TCPPort, fileName, fileSize, uniqueID);
		senderTuple=DataBase.getInstance().findTuple(senderKey);	//a peer sent me the file
		if (senderTuple==null)	//an SN sent me the file
			senderTuple=DataBase.getInstance().findSN(senderKey);
		if (senderTuple==null)	//i'm the file original sender
			senderTuple=final_project.getMyTuple();
		this.senderID=senderID;
	}
	
	public void run(){
		try{
			if (success)	//connection was established
				TCPHandleConnection();
		}
		catch(Exception e){
		}
		finally{
			try {
				if (br!=null)
					br.close();
				if (ps!=null)
					ps.close();
			} catch (IOException e) {}
			//if file exists (no error) - UDP SEND FT TO OTHER PEERS AND SNs
			File file = new File(final_project.currentDir+"/files/"+fileName);
			if (file.exists() && !final_project.isShutDown()){
				prepareFileForTransfer();
				String FTmsg=createFTMessage(fileName, senderID);	//my TCP port with sender ID
				SNsHandler.getInstance().propagateMessageToMyPeers(FTmsg, senderTuple.getPeerID());
				SNsHandler.getInstance().propagateMessageToMySNs(FTmsg, senderTuple.getKey());
			}
			final_project.removeThreadFromLivingList(uniqueID);
		}
	}
	
	private String createFTMessage(String fileName, String senderID) {
		String message = MessageCenter.getInstance().createMessage_FT(Integer.toString(final_project.mainTCPSoc),fileName,Integer.toString(final_project.loadedFiles.get(fileName).length), senderID);
		return message;
	}
	
	private void prepareFileForTransfer(){
		if (!final_project.isShutDown()){
			if (fileName.endsWith(final_project.outputFilePath))
				Logger.getInstance().closeFileAndStopWriting();
			try {
				loadFileForTransfer();
			} catch (IOException e) {}
		}
	}
	
	/**
	 * load a file to be ready to transfer
	 */
	public void loadFileForTransfer() throws IOException{
		if(!final_project.isShutDown()){
			String pictureFilePath = final_project.currentDir+"/files/"+fileName;
			if (final_project.loadedFiles.get(fileName)==null){	//file not already loaded
				//reading the picture file
				try {
					File picture = new File(pictureFilePath);
					FileInputStream in = new FileInputStream(picture);
					byte[] picBytes = new byte[(int) picture.length()];
					in.read(picBytes);
					final_project.loadedFiles.put(fileName, picBytes);
				} catch (Exception e) {
					System.out.println("Problem with picture load "+e.getMessage());
				}
			}
		}
	}
}
